package com.cuit.xsc.weishare.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.cuit.xsc.weishare.R;
import com.cuit.xsc.weishare.logic.MainService;
import com.cuit.xsc.weishare.logic.Task;
import com.cuit.xsc.weishare.model.WeiboBean;
import com.cuit.xsc.weishare.util.BitmapGet;
import com.cuit.xsc.weishare.util.ConfigUtil;
import com.cuit.xsc.weishare.util.LogUtil;
import com.cuit.xsc.weishare.widget.EditBlogView;
import com.cuit.xsc.weishare.widget.EmotionView;

public class CreativeDesignAct extends BaseActivity implements OnClickListener
{
	private EditBlogView etText = null;
	private ImageButton ibLocation = null;
	private ImageButton ibCamera = null;
	private ImageButton ibSmile = null;
	
	private EmotionView expressionGriView = null;
	
	private boolean isShowSmile = true;
	
	private int wordsCount = 0;
	private TextView tvWordsCount = null;
	
	private WeiboBean weiboBean = new WeiboBean();
	
	 /**拍照的照片存储位置*/  
    private static final File PHOTO_DIR = new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera"); 
    private File mCurrentPhotoFile;//照相机拍照得到的图片
    /**用来标识请求照相功能的activity*/  
    private static final int CAMERA_WITH_DATA = 3023;  
    /**用来标识请求gallery的activity*/  
    private static final int PHOTO_PICKED_WITH_DATA = 3021;  
    
    private ImageView ibPicStatus = null;
    
    private Button btPublish = null;
    
   // private ProgressBar pbLocation = null;
    
   // private ProgressBar pbvWaiting = null;
    
    private View progresView = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newblog2);
		
		
		//pbvWaiting = (ProgressBar) findViewById(R.id.pg_progress);
		//pbvWaiting.setVisibility(View.GONE);
		progresView = this.findViewById(R.id.layout_progress);	
		progresView.setVisibility(View.GONE);
		
		etText = (EditBlogView) findViewById(R.id.et_mblog);
		// 页面创建时首先计算剩余字数
		tvWordsCount = (TextView) findViewById(R.id.tv_text_limit);
		tvWordsCount.setOnClickListener(this);
		wordsCount = 280 - etText.getText().length();
		tvWordsCount.setText(wordsCount + "");
		
		
		etText.setOnClickListener(this);
		/// 编辑框
		etText.addTextChangedListener(new TextWatcher() 
		{
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				wordsCount = 280 - etText.getText().length();
				tvWordsCount.setText(wordsCount + "");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after)
			{
			}

			@Override
			public void afterTextChanged(Editable s)
			{
			}
		});
		
		ibLocation = (ImageButton) findViewById(R.id.ib_insert_location);
		ibLocation.setOnClickListener(this);
		
		ibCamera = (ImageButton) findViewById(R.id.ib_insert_pic);
		ibCamera.setOnClickListener(this);
		
		ibSmile = (ImageButton) findViewById(R.id.ib_face_keyboard);
		ibSmile.setOnClickListener(this);
		
		/**
		 * 表情显示框
		 */
		expressionGriView = (EmotionView) findViewById(R.id.emotion_view);
		
		/**
		 * 图片状态图标
		 */
		ibPicStatus = (ImageView) findViewById(R.id.iv_insertpic);
		btPublish = (Button) findViewById(R.id.publish_but);
		btPublish.setOnClickListener(this);
		
		
		
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
		case R.id.et_mblog:
			
			break;
		case R.id.ib_insert_location:
			
			break;
		case R.id.ib_insert_pic:
			doPickPhotoAction();
			break;
		case R.id.ib_face_keyboard:
			if (isShowSmile) {

				/// 加载表情
				expressionGriView.showEmotionBoard();
				ibSmile.setImageResource(R.drawable.btn_insert_keyboard);
			} else {
				
				/// 加载键盘
				expressionGriView.showKeyboard();
				ibSmile.setImageResource(R.drawable.btn_insert_face);
			}
			
			isShowSmile = !isShowSmile;
			break;
		case R.id.publish_but:
			publishWeibo();
			break;

		default:
			break;
		}
		
	}
	
	
	private void doPickPhotoAction() 
	{
		//Context context = CreativeDesignActivity.this;
	
		// Wrap our context to inflate list items using correct theme
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.STR_BACK);
		String[] choices;
		if (weiboBean.getExistImage()) 
		{
			choices = new String[3];
			choices[0] = getString(R.string.STR_CAMERA);  //拍照
			choices[1] = getString(R.string.STR_ALBUM);  //从相册中选择
			choices[2] = getString(R.string.STR_CLEAR);  //清除图片
		}
		else 
		{
			choices = new String[2];
			choices[0] = getString(R.string.STR_CAMERA);  //拍照
			choices[1] = getString(R.string.STR_ALBUM);  //从相册中选择
		}
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices);
	
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(R.string.STR_INSERT_PIC);
		builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() 
		{
					public void onClick(DialogInterface dialog, int which) 
					{
						dialog.dismiss();
						switch (which) 
						{
						case 0:
						{
							String status=Environment.getExternalStorageState();
							if(status.equals(Environment.MEDIA_MOUNTED))//判断是否有SD卡
							{
								doTakePhoto();// 用户点击了从照相机获取
							}
							else
							{
								Toast.makeText(CreativeDesignAct.this, R.string.STR_ABSENT_SD_CARD, Toast.LENGTH_SHORT).show();
							}
							break;
							
						}
						case 1:
							doPickPhotoFromGallery();// 从相册中去获取
							break;
						case 2:
//							clearImage();// 清除图片
							break;
						}
					}
				});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() 
		{
	
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
			
		});
		builder.create().show();
	}
	
	
	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto()
	{
		try
		{
			// Launch camera to take photo for selected contact
			PHOTO_DIR.mkdirs();// 创建照片的存储目录
			mCurrentPhotoFile = new File(PHOTO_DIR, getPhotoFileName());// 给新照的照片文件命名
			
			final Intent intent = getTakePickIntent(mCurrentPhotoFile);
			startActivityForResult(intent, CAMERA_WITH_DATA);
		} 
		catch (ActivityNotFoundException e) 
		{
			Toast.makeText(this, R.string.STR_PHOTO_PICKER_NOT_FOUND_TEXT, Toast.LENGTH_LONG).show();
		}
	}
	
	/**
	 * 用当前时间给取得的图片命名
	 * 
	 */
	private String getPhotoFileName() 
	{
		Date date = new Date(System.currentTimeMillis());
		SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
		return dateFormat.format(date) + ".jpg";
	}
	
	public static Intent getTakePickIntent(File f)
	{
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
		return intent;
	}
	
	/**
	 * 请求Gallery程序
	 * 
	 */
	protected void doPickPhotoFromGallery()
	{
		try
		{
			// Launch picker to choose photo for selected contact
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent.setType("image/*");
			startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
		} 
		catch (ActivityNotFoundException e) 
		{
			Toast.makeText(this, R.string.STR_PHOTO_PICKER_NOT_FOUND_TEXT, Toast.LENGTH_LONG).show();
		}
	}
	
	
	// 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (resultCode != RESULT_OK)
				return;

			Bitmap tmpBitmap = null;
			
			switch (requestCode) {
			/// 照相机拍照的结果
			case CAMERA_WITH_DATA: 
			{// 调用Gallery返回的
				tmpBitmap = BitmapGet.getBitmapFromFile(mCurrentPhotoFile);
				// 下面就是显示照片了
				weiboBean.setExistImage(true);
				break;
			}
			
			/// 相册选图的结果
			case PHOTO_PICKED_WITH_DATA: {
				Uri uri = data.getData();
				LogUtil.e(this, "uri="+uri.toString());
				ContentResolver cr = this.getContentResolver();
				try {
					tmpBitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
					// 下面就是显示照片了
					weiboBean.setExistImage(true);
				} catch (FileNotFoundException e) {
					LogUtil.e(this, e.getMessage());
				}
	            break;
			}
			}
			
			/// 显示缩略图
			if (weiboBean.getExistImage()) {
				LogUtil.i(this, "tmp{w:" + tmpBitmap.getWidth() + ", h:"+ tmpBitmap.getHeight() + "}");
				ibPicStatus.setVisibility(View.VISIBLE);
				
				// 调整大小，当款凸大于440时调整为440
				if (tmpBitmap.getWidth() > ConfigUtil.RAW_IMAGE_WIDTH) 
				{
					Bitmap bitmap = BitmapGet.imageZoomByWidth(tmpBitmap, ConfigUtil.RAW_IMAGE_WIDTH);
					LogUtil.i(this, "bitmap{w:" + bitmap.getWidth() + ", h:"+ bitmap.getHeight() + "}");
					weiboBean.setIcon(bitmap);
				}
				else 
				{
					weiboBean.setIcon(tmpBitmap);
				}
				
				Drawable drawable = new BitmapDrawable(BitmapGet.imageZoomByHeight(tmpBitmap, ConfigUtil.THUMB_IMAGE_HEIGHT));
				ibPicStatus.setBackgroundDrawable(drawable);
				
				LogUtil.i(this, "original{w:" + tmpBitmap.getWidth() + ", h:"
						+ tmpBitmap.getHeight() + "}, new{w:"
						+ drawable.getIntrinsicWidth() + ", h:"
						+ drawable.getIntrinsicHeight() + "}");
			}
		}
		
		
		private void publishWeibo()
		{
			/// 显示进度条
			//pbvWaiting.show(getString(R.string.STR_PUBLISHING));
			
			/// 文本
			weiboBean.setText(etText.getText().toString());
			//weiboBean.setUser(HallActivity.getUser().getScreenName());
			weiboBean.setTime(Calendar.getInstance().getTime());
			/*if (HallActivity.getUser() != null) 
			{
				weiboBean.setProfileUrl(HallActivity.getUser().getProfileImageURL().toString());
			}*/

			if (!weiboBean.getExistImage())
			{
				weiboBean.setIcon(null);
			}
			if (!weiboBean.getExistLocation()) 
			{
				weiboBean.setLatitude(0.0);
				weiboBean.setLongitude(0.0);
			}
			
			if (mCurrentPhotoFile != null)
			{
				weiboBean.setIconUrl(mCurrentPhotoFile.getAbsolutePath());
			}
			LogUtil.i(this, "test1:"+weiboBean.getText());
			LogUtil.i(this, "test2:"+weiboBean.getIconUrl());
			
			//showWaitingDialog("please watting.");
			progresView.setVisibility(View.VISIBLE);
			Map map = new HashMap();
			map.put("weiboBean", weiboBean);
			Task task = new Task(Task.PUBLISH_WEIBO,map);
			/// 发送消息发布微博
			MainService.addTask(task);	
			
		}
		
		@Override
		public void refresh(Object... param)
		{
			//dismissWaitingDialog();
			progresView.setVisibility(View.GONE);
			int flag = ((Integer) param[0]).intValue();
			switch (flag)
			{
			case Task.PUBLISH_WEIBO:
				String result = (String) param[1];
				if (result.equals("success"))
				{
					Toast.makeText(this, "微博发布成功！", Toast.LENGTH_SHORT);
					finish();
				}
				else
				{
					Toast.makeText(this, "对不起，你的微博发布失败！", Toast.LENGTH_SHORT);
				}
				break;
			
			}
			
			
		}
		
		
		


}
